package cn.edu.cdu.argorithm.impl;

import cn.edu.cdu.argorithm.IReverseKGroup;
import cn.edu.cdu.argorithm.common.ListNode;

public class ReverseKGroupSolutions implements IReverseKGroup {

    @Override
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(-1, head), prev = dummy;
        while(true) {
            ListNode tail = prev;
            for(int i = 0; i < k; i++) {
                tail = tail.next;
                if(tail == null) {
                    return dummy.next;
                }
            }

            ListNode curr = prev.next;
            for(int i = 0; i < k - 1; i++) {
                ListNode next = curr.next;
                curr.next = next.next;
                next.next = prev.next;
                prev.next = next;
            }
            prev = curr;
        }
    }
}
